config_but = 'config.but'

chapters = 5
appendices = 9

htmls = Split('IndexPage.html Contents.html') \
	+ map(lambda ch: 'Chapter' + str(ch + 1) + '.html', range(chapters)) \
	+ map(lambda ap: 'Appendix' + chr(ord('A') + ap) + '.html', range(appendices))
fixed_htmls = map(lambda fn: 'fixed/'+fn, htmls)

chm_config_but = 'chm_config.but'

buts = Split("""
	intro.but
	tutorial.but
	usage.but
	script.but
	var.but
	labels.but
	jumps.but
	pages.but
	sections.but
	usection.but
	functions.but
	callback.but
	attributes.but
	compilerflags.but
	basic.but
	registry.but
	generalpurpose.but
	flowcontrol.but
	file.but
	uninstall.but
	misc.but
	string.but
	stack.but
	int.but
	reboot.but
	log.but
	sec.but
	ui.but
	langs.but
	plugin.but
	silent.but
	compiler.but
	defines.but
	modernui.but
	library.but
	usefulfunc.but
	usefulinfos.but
	headers.but
	history.but
	build.but
	credits.but
	license.but
""")

import os
import re

Import('halibut env build_chm')

env.Append(ENV = {'PATH' : os.environ['PATH']})
env['HALIBUT'] = halibut

build_dir = Dir(GetBuildPath('.')).abspath

replacement = '<a href="%s/\\1/' % env.subst('$PREFIX_DATA')

def fix_html(target, source, env):
	for i in range(len(source)):
		data = open(source[i].path,'rb').read()
		data = re.sub('<a href="../(Include|Stubs|Plugins|Contrib)/', replacement, data)
		open(target[i].path,'wb').write(data)
	return None

if build_chm:
	hhc_action = Action(r'cd %s && hhc nsis.hhp' % build_dir)

	chm_builder = Builder(
		action = [
			Copy(build_dir, '${SOURCE.dir}/../style.css'),
			Copy(build_dir, '${SOURCE.dir}/chmlink.js'),
			Copy(build_dir, '${SOURCE.dir}/nsis.hhp'),
			Action(
				['${HALIBUT[0].abspath} ${SOURCES.abspath}'],
				chdir = build_dir
			),
			hhc_action
		]
	)

	env.Append(BUILDERS = {'HalibutCHM' : chm_builder})

	# fix hhc.exe reverse return value - UGLY
	old_spawn = env['SPAWN']
	def new_spawn(*args, **kw):
		result = old_spawn(*args, **kw)
		if 'hhc' in args[3]:
			return not result
		else:
			return result
	env['SPAWN'] = new_spawn

	# build CHM
	chm = env.HalibutCHM('NSIS.chm', [chm_config_but] + buts)
	env.Depends(chm, halibut)
	env.Depends(chm, '#Docs/style.css')
	env.Depends(chm, 'chmlink.js')
	env.Depends(chm, 'nsis.hhp')
	env.DistributeDoc(chm)

else:
	html_builder = Builder(
		action = [
			Copy(build_dir, '${SOURCE.dir}/../style.css'),
			Action(['${HALIBUT[0].abspath} ${SOURCES.abspath}'], chdir = build_dir)
		]
	)
	
	html_fixer = Builder(action = fix_html, suffix = '.html', src_suffix = '.html')

	env.Append(BUILDERS = {'Halibut' : html_builder, 'FixHTML': html_fixer})

	html = env.Halibut(htmls, [config_but] + buts)
	env.Depends(html, halibut)
	env.DistributeDocs('#Docs/style.css')

	if env['PLATFORM'] == 'win32':
		env.DistributeDocs(html)
	else:
		fixed_html = env.FixHTML(fixed_htmls, htmls)
		env.DistributeDocs(fixed_html)
